package cc.vv.mvp.activity;

import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.view.ViewGroup;

import cc.vv.baselibrary.activity.UtimingBaseActivity;
import cc.vv.baselibrary.bean.base.BaseEntityObj;
import cc.vv.mvp.binder.BaseDataBinder;
import cc.vv.mvp.delegate.XDelegate;

/**
 * MVP模式的Activity基类
 * Created by sun.li on 2018/6/5.
 *
 * @author sun.li
 */

public abstract class BaseActivityMVP<T extends XDelegate> extends UtimingBaseActivity {

    /**
     * 视图托管类对象
     */
    protected T viewDelegate;

    /**
     * 公共数据视图绑定控制器对象
     */
    protected BaseDataBinder binder;

    public BaseActivityMVP() {
        try {
            viewDelegate = getDelegateClass().newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("create IDelegate error");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("create IDelegate error");
        }
    }

    @CallSuper
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        viewDelegate.create(getLayoutInflater(), null, savedInstanceState);
        setContentView(viewDelegate.getRootView());
        binder = getDataBinder();
        super.onCreate(savedInstanceState);
        viewDelegate.initWidget();
        initData();
        bindEvenListener();
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        super.initView(bundle);
        if (null != viewDelegate && null != viewDelegate.getRootView()) {
            try {
                ViewGroup.LayoutParams layoutParams = viewDelegate.getRootView().getLayoutParams();
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                viewDelegate.getRootView().setLayoutParams(layoutParams);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始化界面数据
     */
    protected abstract void initData();

    /**
     * 注册界面控件点击事件
     */
    protected abstract void bindEvenListener();

    /**
     * 指定界面的视图控制器，必须指定
     */
    protected abstract Class<T> getDelegateClass();

    /**
     * 公共数据视图绑定控制器数据对象
     */
    public abstract BaseDataBinder getDataBinder();

    /**
     * 根据数据刷新视图
     */
    public <D extends BaseEntityObj> void notifyModelChanged(D data) {
        if (binder != null)
            binder.viewBindModel(viewDelegate, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /* 界面关闭解除视图绑定操作*/
        viewDelegate = null;
    }
}
